angular.module('mvcRestBaseApp')
    .factory('Category', ['$http',
        function($http) {
            var categoryCache = {};
            var shopCategoriesPromise = null;
            var isInWeixin = isWeiXin();
            var model = {
                listShopCategories: function() {
                    if (isInWeixin && shopCategoriesPromise) {
                        return shopCategoriesPromise;
                    }
                    var promise = new Promise(function (resolve, reject) {
                        $http.get('/wechatshop/category/shop_categories')
                            .success(ngPromiseHandler(resolve, reject))
                            .error(reject);
                    });
                    if (isInWeixin) {
                        shopCategoriesPromise = promise;
                    }
                    return promise;
                },
                createShopCategory: function(name, logoUrl) {
                    return new Promise(function(resolve, reject) {
                        if(!name || !name.trim()) {
                            reject('empty shop category name');
                            return;
                        }
                        $http({
                            url: '/wechatshop/category/create_shop_category',
                            method: 'POST',
                            data: $.param({
                                name: name,
                                logoUrl: logoUrl
                            }),
                            headers: formHeaders
                        }).success(ngPromiseHandler(resolve, reject))
                            .error(reject);
                    });
                },
                getById: function(id) {
                    if(!id) {
                        return new Promise(function(resolve, reject) {
                            reject('');
                        });
                    }
                    if(categoryCache[id]) {
                        return categoryCache[id];
                    }
                    var promise = new Promise(function(resolve, reject) {
                        $http.get('/wechatshop/category/shop_category/' + id)
                            .success(ngPromiseHandler(resolve, reject))
                            .error(reject);
                    });
                    categoryCache[id] = promise;
                    return promise;
                }
            };
            return model;
        }]);